$(function(){
    var media = $('#media');
    media.on("show", function() {
        media.find('a.btn').on("click", function(e) {
            media.modal('hide');
        });
    });

    media.on("hide", function() {
        media.find('a.btn').off("click");
    });

    media.on("hidden", function() {
        media.remove();
    });

});

function uploadClick(obj){
    obj = $(obj);
    obj.parent().find('li').removeClass('active');
    obj.addClass('active');
    var upload = $('.upload-image');
    var library = $('.library-image');
    upload.show();
    library.hide();
}

function libraryClick(obj){
    obj = $(obj);
    obj.parent().find('li').removeClass('active');
    obj.addClass('active');
    var upload = $('.upload-image');
    var library = $('.library-image');
    upload.hide();
    library.show();
}

function imageClick(obj){
    obj = $(obj);
    obj.parent().find('div').removeClass('img-clicked');
    obj.addClass('img-clicked');

    var caption = obj.attr("caption");
    var description = obj.attr("description");
    var alt = obj.find('img').attr('alt');
    var title = obj.find('img').attr('title');
    var iid = obj.attr('iid');

    $('#title-image').val(title);
    $('#caption-image').val(caption);
    $('#alt-image').val(alt);
    $('#description-image').val(description);

    var src = obj.find('img').attr('src');
    var filename = src.substring(src.lastIndexOf('/')+1);
    var info_image = $('#info-image');
    info_image.find('img').attr('src', src);
    info_image.find('.remove-image').attr('iid', iid);
}

function useImage(obj){
    obj = $(obj);
    var src = $('#info-image').find('img').attr('src');
    var filename = src.substring(src.lastIndexOf('/')+1);
    if($("#bootbox-regular").attr('item') == "1"){
        var alt = $('#alt-image').val();
        var caption = $('#caption-image').val();
        var title = $('#title-image').val();
        var img = '<img alt="'+alt+'" title="'+title+'" src="'+src+'" style="-webkit-box-shadow:rgba(0, 0, 0, 0.2) 0px 1px 3px; -webkit-transition:all 0.2s ease-in-out; border:1px solid rgb(194, 194, 194); box-shadow:rgba(0, 0, 0, 0.298039) 0px 1px 3px; display:block; height:auto; margin:0px auto; max-width:90%; transition:all 0.2s ease-in-out; vertical-align:middle;"><p style="text-align:center"><em>'+caption+'</em></p>';
        CKEDITOR.instances['editor_vn'].insertHtml(img);

    }else{
        var image = $('.product-item-img');
        image.find('img').attr('src', src);
        image.find('input[name="image"]').val(filename);
    }
    $('#media').modal('toggle');
}


